package com.styletransfer.security;

import com.styletransfer.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT请求过滤器
 * 
 * 这个类用于拦截所有HTTP请求，检查请求头中是否包含有效的JWT令牌。
 * 如果令牌有效，则将用户信息设置到Spring Security的上下文中，以便后续的请求处理。
 * 同时，会保存用户ID，以便其他组件可以访问。
 */
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    
    @Autowired
    private CustomUserDetailsService userDetailsService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 过滤请求
     * 
     * @param request 请求
     * @param response 响应
     * @param chain 过滤器链
     * @throws ServletException Servlet异常
     * @throws IOException IO异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        
        // 获取Authorization请求头
        final String authorizationHeader = request.getHeader("Authorization");
        
        String username = null;
        String jwt = null;
        Long userId = null;
        
        // 检查Authorization请求头是否存在且以"Bearer "开头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 提取JWT令牌
            jwt = authorizationHeader.substring(7);
            try {
                // 从JWT令牌中提取用户名和用户ID
                username = jwtUtil.getUsernameFromToken(jwt);
                userId = jwtUtil.getUserIdFromToken(jwt);
                
                // 将用户ID保存到请求属性中，以便其他组件可以访问
                request.setAttribute("userId", userId);
            } catch (Exception e) {
                // 令牌无效或已过期，不做任何处理，继续执行过滤器链
            }
        }
        
        // 如果成功提取了用户名，且当前没有认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 加载用户详情
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            
            // 验证JWT令牌
            if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
                // 创建认证令牌，并将用户ID保存到认证详情中
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                
                // 设置认证详情，包括用户ID
                WebAuthenticationDetailsSource detailsSource = new WebAuthenticationDetailsSource();
                authToken.setDetails(detailsSource.buildDetails(request));
                
                // 设置认证信息到Spring Security上下文
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        
        // 继续执行过滤器链
        chain.doFilter(request, response);
    }
}
